//Given an integer array nums, return all the triplets [nums[i], nums[j], nums[
//k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. 
//
// Notice that the solution set must not contain duplicate triplets. 
//
// 
// Example 1: 
// Input: nums = [-1,0,1,2,-1,-4]
//Output: [[-1,-1,2],[-1,0,1]]
// Example 2: 
// Input: nums = []
//Output: []
// Example 3: 
// Input: nums = [0]
//Output: []
// 
// 
// Constraints: 
//
// 
// 0 <= nums.length <= 3000 
// -10⁵ <= nums[i] <= 10⁵ 
// 
// Related Topics Array Two Pointers Sorting 👍 14334 👎 1388


package leetcode.editor.en;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _15_ThreeSum {
    public static void main(String[] args) {
        Solution solution = new _15_ThreeSum().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            List<List<Integer>> re = new ArrayList<>();
            if (nums.length<3){
                return re;
            }
            Arrays.sort(nums);
            for (int i = 0; i < nums.length; i++) {
                if (nums[i]>0){
                    break;
                }
                if (i>0&&nums[i]==nums[i-1]) {
                    continue;
                }
                int l = i+1;
                int r = nums.length-1;
                while (l<r){
                    int sum = nums[i] + nums[l] + nums[r];
                    if (sum ==0) {
                        re.add(Arrays.asList(nums[i], nums[l], nums[r]));
                        while (l<r&&nums[l] == nums[l+1]){
                            l++;
                        }
                        while (l<r&&nums[r]==nums[r-1]){
                            r--;
                        }

                        l++;
                        r--;
                    }else if (sum>0){
                        r--;
                    }else {
                        l++;
                    }
                }
            }
            return re;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}